package com.ahy231.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.Calendar;

/**
 * @author ahy231
 * @date 2021/7/23 13:31
 * @description JWT 工具类
 */
@Component
public class JWTUtil {

    // 过期时间为 24 个小时
    private static int EXPIRE_TIME = 86400000;
    // 密钥
    private static String SECRET = "WHATEVERIAM";

    /**
     * 生成 token
     */
    public String createToken(long userId) {
        try {
            Calendar deadline = Calendar.getInstance();
            deadline.add(Calendar.MILLISECOND, EXPIRE_TIME);

            Algorithm algorithm = Algorithm.HMAC256(SECRET);

            return JWT.create()
                    .withClaim("userId", userId)
                    .withExpiresAt(deadline.getTime())
                    .sign(algorithm);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 验证 token 是否合法
     */
    public boolean verify(String token, long userId) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withClaim("userId", userId)
                    .build();
            verifier.verify(token);
            return true;
        } catch (AlgorithmMismatchException | SignatureVerificationException | TokenExpiredException | InvalidClaimException | JWTDecodeException e) {
            return false;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 从 token 中获取 openId
     */
    public static Long getUserId(String token) {
        try {
            return JWT.decode(token).getClaim("userId").asLong();
        } catch (JWTDecodeException e) {
            return null;
        }
    }
}
